BUI.use(['bui/overlay','bui/slider','bui/menu','bui/uploader','bui/select','bui/data','bui/form'],function(Overlay,Slider,Menu,Uploader,Select,Data,Form){
	function showDialog(msg){
		 BUI.Message.Alert(msg,function(){},'info');
	}
	var dialog = new Overlay.Dialog({
		title:'添加奖品',
		width:600,
		height:600,
		mask:true,
		maskShared:false,
		buttons:[{
			text:'添加',
			elCls : 'button button-primary',
			handler : function(){
				if(giftform.isValid()){
					var picurl = $(".js-picurl").val();
					var giftname = $(".js-giftname").val();
					var jplx = $(".js-jplx").val();
					var lott = $(".js-lott").val();
					var jf = $(".js-jf").val();
					var promoid = $(".js-promoid").val();
					var tagid = $(".js-tagid").val();
					var medal_id = $(".js-medal_id").val();
					var medal_name = $(".js-medal_name").val();
					var medal_pic = $(".js-medal_pic").val();
					var gifturl = $(".js-gifturl").val();
					var price = $(".js-price").val();
					var quantity = $(".js-count").val();
					var kmlist = $(".js-kmlist").val();
					var detail = $(".js-detail").val();
					$.ajax(
					{"url":"/?m=Kxdr&c=Gift&a=add_gift",	
						"data":{"picurl":picurl,
								"giftname":giftname,
								"jplx":jplx,
								"lott":lott,
								"jf":jf,
								"promoid":promoid,
								"tagid":tagid,
								"medal_id":medal_id,
								"medal_name":medal_name,
								"medal_pic":medal_pic,
								"gifturl":gifturl,
								"price":price,
								"quantity":quantity,
								"kmlist":kmlist,
								"detail":detail},					
						"dataType": "json",
						"success":function(data,status){
							if(data.hasError){
								alert("设置出错！"+data.error);
							}else{
								location.href="/?m=Kxdr&c=Gift"
							}
						}
					});
				}
			}
		  },{
			text:'取消',
			elCls : 'button button-mini',
			handler : function(){
			  //do some thing
			  this.close();
			}
		  }],
		contentId:"content"
	});
	$(".js-get-metal").on("click",function(){
		$.ajax(
		{"url":"/?m=Kxdr&c=medal&a=get_medal_as_gift",					
			"dataType": "json",
			"success":function(data,status){
				var msg="";
				if(data.hasError){
					msg="<h2>出错！</h2><br />"+data.error;
				}else{
					msg="<h2>请选择勋章：</h2><br />";
					for(var i=0;i<data.data.length;i++){
						msg+='<li><span class="md'+data.data[i].id+'"><span> <img src="'+data.data[i].pic_url+'_20x20.jpg" />  '+data.data[i].title+'</span></span><button class="button button-mini umps" data-id="'+data.data[i].id+'" data-pic="'+data.data[i].pic_url+'" data-name="'+data.data[i].title+'" type="button">选择</button></li>';
					}
				}
				BUI.Message.Show({
					"msg" : msg,
					"icon" : 'question',
					"mask":false,
					"buttons" : [
					  {
						text:'确认',
						elCls : 'button js-msg',
						handler : function(){
						  this.close();
						}
					  }
					]
				});
				$(".umps").on("click",function(){
					$(".umps").removeClass("button-danger");
					$(this).addClass("button-danger");
					$(".js-giftname").val($(this).attr("data-name"));
					$(".js-medal_id").val($(this).attr("data-id"));
					$(".js-medal_pic").val($(this).attr("data-pic"));
					$(".js-medal_name").val($(this).attr("data-name"));
					$(".medal").empty();
					$($(".md"+$(this).attr("data-id")).html()).appendTo(".medal");
					
					var html = "直接出现在勋章列表";
					$(".js-detail").val(html);
					$(".js-msg").click();
					$(".js-giftname").blur();
				});
			}
		});
	});
	$(".js-get-prom").on("click",function(){
		$.ajax(
		{"url":"/?m=shopadmin&c=api&a=get_prom",					
			"dataType": "json",
			"success":function(data,status){
				var msg="";
				if(data.hasError){
					msg="<h2>出错！</h2><br />"+data.error;
				}else{
					msg="<h2>请选择折扣：</h2><br />";
					for(var i=0;i<data.data.length;i++){
						msg+='<li> 开始：'+data.data[i].start_time+' 结束：'+data.data[i].end_time+'  '+data.data[i].custom_title+'<button class="button button-mini umps" data-numiid="'+data.data[i].notice+'" data-promid="'+data.data[i].id+'" data-tagid="'+data.data[i].tag_id+'" data-name="'+data.data[i].custom_title+'" type="button">选择</button></li>';
					}
				}
				BUI.Message.Show({
					"msg" : msg,
					"icon" : 'question',
					"mask":false,
					"buttons" : [
					  {
						text:'确认',
						elCls : 'button js-msg',
						handler : function(){
						  this.close();
						}
					  }
		   
					]
				});
				$(".umps").on("click",function(){
					$(".umps").removeClass("button-danger");
					$(this).addClass("button-danger");
					$(".js-giftname").val($(this).attr("data-name"));
					$(".js-promoid").val($(this).attr("data-promid"));
					$(".js-tagid").val($(this).attr("data-tagid"));
					var html = "中奖后在商品详情页即可看到专属折扣：http://item.taobao.com/item.html?id="+$(this).attr("data-numiid");
					$(".js-detail").val(html);
					$(".js-msg").click();
					$(".js-giftname").blur();
				});
			}
		});
	});
	$(".js-addgift").on("click",function(){
		giftstore.load();
		dialog.show();
	});
	$(".js-refond").on("click",function(){
		var gid = $(this).attr("data-gid");
		$.ajax(
			{"url":"/?m=Kxdr&c=Gift&a=refond_gift",	
				"data":{"gid":gid},							
				"dataType": "json",
				"success":function(data,status){
					if(data.hasError){
						alert("出错！"+data.error);
					}else{
						location.href="/?m=Kxdr&c=Gift";
					}
				}
			}
		  );
	});
	$(".js-remove").on("click",function(){
		var gid = $(this).attr("data-gid");
		BUI.Message.Show({
					"msg" : "<h2>您确定要删除这个奖品吗？</h2>",
					"icon" : 'question',
					"mask":false,
					"buttons" : [
					  {
						text:'删除',
						elCls : 'button js-msg',
						handler : function(){
						  $.ajax(
							{"url":"/?m=Kxdr&c=Gift&a=remove_gift",	
								"data":{"gid":gid},							
								"dataType": "json",
								"success":function(data,status){
									if(data.hasError){
										alert("出错！"+data.error);
									}else{
										location.href="/?m=Kxdr&c=Gift";
									}
								}
							}
						  );
						}
					  },{
						text:'取消',
						elCls : 'button js-msg',
						handler : function(){
						  this.close();
						}
					  }
		   
					]
				});
	});
	var km_dialog =  new Overlay.Dialog({
		title:'已中奖的卡密',
		width:600,
		height:300,
		mask:false,
		contentId:"zjkm"
	});
	$(".kmlist").on("click",function(){
		km_dialog.show();
	});
	var uploader = new Uploader.Uploader({
        render: '#J_Uploader',
		name:"userfile",
        url: '/services/img/apiupload/SaveImg.php',
        //可以直接在这里直接设置成功的回调
        success: function(result){
			if(result.status==0){
				showDialog("登录超时，请重新登录");
				return;
			}
			$(".js-picurl").val(result.url);
			$(".js-picview").attr("src",result.url+"_150x150.jpg");
        },
        //isSuccess : function(result){},
        //失败的回调
        error: function(result){
			showDialog("上传文件失败");
        }
      }).render();
	
	var giftstore = new Data.Store({  //自动读取后台奖品数据
      url : '/?m=Kxdr&c=Gift&a=get_gift_types',
      autoLoad : false,
    });
    select6 = new Select.Select({  
          render:'#s6',
          valueField:'.js-jplx',
          store:giftstore
        });
    select6.render();
    select6.on('change', function(ev){
		$(".js-cishu").hide();
		$(".js-zhekou").hide();
		$(".js-km").hide();
		$(".js-jifen").hide();
		$(".js-link").hide();
		$(".js-rongyu").hide();
		$(".js-jiazhi").show();
		$(".js-shuliang").show();
		switch(ev.item.value){
			case 1:
			// 实物
			$(".js-link").show();
			break;
			case 4:
			// 卡密
			$(".js-km").show();
			$(".js-shuliang").hide();
			break;
			case 5:
			// 超低折扣
			$(".js-zhekou").show();
			break;
			case 7:
			// 抽奖次数
			$(".js-cishu").show();
			$(".js-jiazhi").hide();
			break;
			case 10:
			// 积分
			$(".js-jifen").show();
			$(".js-jiazhi").hide();
			break;
			case 11:
			// 荣誉
			$(".js-jiazhi").hide();
			$(".js-rongyu").show();
			$(".js-jiazhi").hide();
			break;
		}
    });
	var giftform =  new Form.HForm({
        srcNode : '#J_Form',
        defaultChildCfg : {
          validEvent : 'blur' //移除时进行验证
        }
      });
	giftform.render();
	$(".send_log").on("click",function(){
		var sendid = $(this).attr("data-sendid");
		var ugid = $(this).attr("data-ugid");
		var uid = $(this).attr("data-uid");
		get_wlinfo(sendid,ugid,uid);
	});
	function get_wlinfo(sendid,ugid,uid){
		$.ajax({"url":"/?m=kxdr&c=event&a=get_send_log",					
			"dataType": "json",
			"data":{"sendid":sendid,"ugid":ugid,"uid":uid},
			"success":function(data,status){
				if(data.hasError){
					alert("读取出错！");
				}else{
					$(".wls option[value="+data.wl.wlid+"]").attr("selected", "selected"); 
					$(".mywl option[value="+data.wl.wlid+"]").attr("selected", "selected"); 
					var html = get_wl_html(data);
					var dialog = new Overlay.Dialog({
						title:"请查看快递信息：",
						width:600,
						height:360,
						mask:true,
						maskShared:false,
						buttons:[{
							text:'关闭',
							elCls : 'button button-primary',
							handler : function(){}
						},{
							text:'修改',
							elCls : 'button',
							handler : function(){
								save_wlinfo("update",ugid,uid,sendid);
								dialog.destroy();
							}
						}],
						bodyContent:html
					});
					dialog.show();
				}
			}
		});
	}
	$(".send_gift").on("click",function(){
		var ugid = $(this).attr("data-ugid");
		var uid = $(this).attr("data-uid");
		$.ajax({"url":"/?m=kxdr&c=event&a=get_user_addr",					
			"dataType": "json",
			"data":{"ugid":ugid,"uid":uid},
			"success":function(data,status){
				if(data.hasError){
					showDialog("抱歉，该用户没有留下地址，不能发奖。");
				}else{
					var html = get_wl_html(data);
					var dialog = new Overlay.Dialog({
						title:"请输入快递单号",
						width:600,
						height:360,
						mask:true,
						maskShared:false,
						buttons:[{
							text:'确认',
							elCls : 'button button-primary',
							handler : function(){
								save_wlinfo("add",ugid,uid);
								dialog.destroy();
							}
						  },{
							text:'取消',
							elCls : 'button button-info',
							handler : function(){
							  //do some thing
							  this.destroy();
							}
						  }],
						bodyContent:html
					});
					dialog.show();
				}
			}
		});
	});
	function save_wlinfo(action,ugid,uid,sendid){
		var province = $(".province").text();
		var city = $(".city").text();
		var city_part = $(".city_part").text();
		var addr = $(".addr").text();
		var name = $(".name").text();
		var tel = $(".tel").text();
		var wlmc = $(".mywl").find("option:selected").text();;
		var wlid = $(".mywl").val();
		var wlcode = $(".wlcode").val();
		if(!wlcode){
			alert("请填入物流单号！");
			return;
		}
		$(".wls option[value="+wlid+"]").attr("selected", "selected"); 
		$.ajax({"url":"/?m=kxdr&c=event&a=send_gift&ac="+action,					
			"dataType": "json",
			"data":{"wlmc":wlmc,"wlid":wlid,"wlcode":wlcode,"ugid":ugid,"uid":uid,"province":province,"city":city,"city_part":city_part,"addr":addr,"name":name,"tel":tel,"sendid":sendid},
			"success":function(data,status){
				if(data.hasError){
					alert("这个奖品已经发货了！");
					return;
				}else{
					$(".send_gift"+ugid).removeClass("button-danger").unbind("click").text("单号").attr("data-sendid",data.id).on("click",function(){alert(wlcode)});;
				}
			}
		});
	}
	function get_wl_html(data){
		var wl = $(".wl").clone();
			wl.children(".wls").addClass("mywl").removeClass("wls");
		var html = ("<div class=\"form-horizontal offset2 \">");
			html+=(" <div class=\"control-group span8\">");
			html+=("     <label class=\"control-label\">用户地址为：</label>");
			html+=("     <div class=\"controls\">");
			html+=("       <span class=\"province\">"+data.address.province+"</span><span class=\"city\">"+data.address.city+"</span><span class=\"city_part\">"+data.address.city_part+"</span><span class=\"addr\">"+data.address.address+"</span>");
			html+=("     </div>");
			html+=(" </div>");
			html+=(" <div class=\"control-group span8\">");
			html+=("     <label class=\"control-label\">收件人：</label>");
			html+=("     <div class=\"controls\">");
			html+=("       <span class=\"name\">"+data.address.name+"</span>");
			html+=("     </div>");
			html+=(" </div>");
			html+=(" <div class=\"control-group span8\">");
			html+=("     <label class=\"control-label\">电话：</label>");
			html+=("     <div class=\"controls\">");
			html+=("       <span class=\"tel\">"+data.address.tel+"</span>");
			html+=("     </div>");
			html+=("   </div>");
			html+=("  <div class=\"control-group span8\">");
			html+=("     <label class=\"control-label\">选择物流：</label>");
			html+=("     <div class=\"controls\">");
			html+=("       "+wl.html()+"");
			html+=("     </div>");
			html+=("  </div>");
			html+=("  <div class=\"control-group span8\">");
			html+=("     <label class=\"control-label\">快递单号：</label>");
			html+=("     <div class=\"controls\">");
			html+=("       <input type=\"text\" class=\"control-text wlcode\" value=\""+data.wl.wlcode+"\">");
			html+=("     </div>");
			html+=("  </div>");
			html+=("</div>");
			return html;
	}
	
	var pic = new Uploader.Uploader({
        render: '#home_flag_up',
		name:"userfile",
        url: '/services/img/apiupload/SaveImg.php',
        //可以直接在这里直接设置成功的回调
        success: function(result){
			if(result.status==0){
				showDialog("登录超时，请重新登录");
				return;
			}
			$(".home_flag").val(result.url);
			$(".home_flag_pic").attr("src",result.url+"_40x40");
        },
        //isSuccess : function(result){},
        //失败的回调
        error: function(result){
			showDialog("上传文件失败");
        }
    }).render();
	
	var pic = new Uploader.Uploader({
        render: '#guest_flag_up',
		name:"userfile",
        url: '/services/img/apiupload/SaveImg.php',
        //可以直接在这里直接设置成功的回调
        success: function(result){
			if(result.status==0){
				showDialog("登录超时，请重新登录");
				return;
			}
			$(".guest_flag").val(result.url);
			$(".guest_flag_pic").attr("src",result.url+"_40x40");
        },
        //isSuccess : function(result){},
        //失败的回调
        error: function(result){
			showDialog("上传文件失败");
        }
    }).render();
});